<template>
  <div class="connect">

    <div style="position: absolute; opacity: 1; z-index: 100;right: 1px;"   class="box">
            <div  :id="'subOutputRank'+index" v-for="(item,index) in select_table" class="item_box" style="background-color: #fff;width:100mm;height:113mm;" ref="custom_table">
                <div class="print_time">
                    <span>打印时间:2023-12-22 14:16:23</span>
                    <div class="print_jd_font" style="">
                      <div style="height: 3mm;font-size: 3mm;">950616</div>
                      <div style="height: 3mm;font-size: 3mm;">www.jdw1.com</div>
                    </div>
                </div>
                <div class="print_code">

                </div>
                <div class="print_jd_code">
                  <span>
                    JDVX99999999999-9-9-;JDVX99999999999-9-9-
                  </span>
                  <span>
                    999kg
                  </span>
                </div>
                <div class="print_info_one">
                  <div class="print_info_one_left">
                    <p class="print_info_one_left_top">
                      <span>特惠送</span>
                      <span>隔日达</span>
                      <span>鸡毛值</span>
                      <span>【C】</span>
                      <span>众</span>
                    </p>
                    <div class="print_info_one_left_address">
                      <div class="print_info_one_left_address_left">
                          <p class="action_address">始发地：北京通州北京通州北京通州北京通州</p>
                          <p class="action_address_coed">01-W06-01</p>
                      </div>
                      <div class="print_info_one_left_address_right">
                        <p class="action_address">目的地：北京通州北京通州北京通州北京通州</p>
                        <p class="action_address_coed">01-W06-01</p>
                      </div>
                    </div>
                    <div class="consignee_information">
                      <div class="consignee_information_title">
                        收件信息
                      </div>
                      <div>
                        <p class="consignee_information_info">
                            辽宁省大连市沙河口区金华中原20号楼6单元801室
                            辽宁省大连市沙河口区金华中原20号楼6单元801室
                            辽宁省大连市沙河口区金华中原20号楼6单元801室
                            辽宁省大连市沙河口区金华中原20号楼6单元801室
                        </p>
                        <p class="consignee_information_user">
                          <span>郑^-^ </span>
                          <span>176****5885</span>
                        </p>
                      </div>
                    </div>

                  </div>

                </div>
            </div>
    </div>
    <div class="connect_box">
      <el-form :inline="true" ref="formInline" :model="formInline" class="demo-form-inline">
        <el-form-item :label="$t('Order_module.Batch_number')">
          <!-- 批次号 -->
          <el-input v-model="formInline.manifestNo" :placeholder="$t('Order_module.Batch_number')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('Order_module.PRINT_STATUS')">
          <!-- 打印状态 -->
          <el-select v-model="formInline.printStatus":placeholder="$t('Order_module.PRINT_STATUS')">
              <el-option
                v-for="item in printStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item :label="$t('public.Timing')">
          <!-- 选择时间 -->
           <el-date-picker
                value-format='yyyy-MM-dd HH:mm:ss'
                v-model="formInline.dataTimevalue"
                type="datetimerange"
                range-separator="-"
                @change="dataTimeChange"
                :start-placeholder="$t('public.Timing')"
                :end-placeholder="$t('public.Timing')">
              </el-date-picker>
        </el-form-item>
          <el-button type="primary" @click="getList" >{{$t('public.query')}}</el-button>
          <el-button @click="resetForm('formInline')">{{$t('public.resetting')}}</el-button>
        </el-form-item>
      </el-form>
      <div class="btns_ayyay">
         <el-button  @click="doPrint">{{$t('Order_module.Print_face_sheet')}}</el-button>
         <!-- getPdf('#subOutputRank','我的pdf' , list.length , true) -->
         <el-button  @click="getPdf('#subOutputRank','我的pdf' , select_table.length ,false)" >预览</el-button>
         <el-button>{{$t('Order_module.Export_Face_Sheet')}}</el-button>
         <el-button @click="pullOrderNum()">{{$t('public.Pull_order_number')}}</el-button>
         <el-button>{{$t('Order_module.Driver_Download')}}</el-button>
      </div>
        <el-table :data="tableData" border stripe style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column align="center" type="selection" width="55"> </el-table-column>
         <!-- // manifestNo: null//批次编号,
          // userName: null//用户名称,
          // successNum: null//拉取成功订单数,
          // failNum: null//拉取失败订单数,
          // printedNum: null//已打印订单数,
          // notPrintedNum: null//未打印订单数, -->
          <!--批次编号  -->
          <el-table-column align="center" prop="manifestNo" :label="$t('Order_module.Batch_number')"  min-width="180"> </el-table-column>
          <!-- 用户名称 -->
          <el-table-column align="center" prop="userName" :label="$t('Order_module.UserName')"  min-width="180"> </el-table-column>
          <!-- 订单总数 -->
          <el-table-column align="center" prop="orderNumbers" :label="$t('public.Total_number_of_Orders')"  min-width="180"> </el-table-column>
          <!-- 拉取成功订单数 -->
          <el-table-column align="center" prop="successNum" :label="$t('public.Number_of_successfully_pulled_orders')"  min-width="180"> </el-table-column>
          <!-- 拉取失败订单数 -->
          <el-table-column align="center" prop="failNum" :label="$t('public.Number_of_error_pulled_orders')"  min-width="180"> </el-table-column>
          <!-- 已打印订单数 -->
          <el-table-column align="center" prop="printedNum" :label="$t('public.Number_of_printed_orders')"  min-width="180"> </el-table-column>
          <!-- 未打印订单数 -->
          <el-table-column align="center" prop="notPrintedNum" :label="$t('public.Unprinted_orders')"  min-width="180"> </el-table-column>

        </el-table>
        <div style="margin-top: 20px;"></div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[10, 50, 200, 400]"
          :page-size="limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
    </div>

  </div>
</template>

<script>

  import {
    manifest_list,
    manifest_dataCheck,
    manifest_billing
  } from '@/api/wqzApi'
  export default {
    components: {},
    data() {
      return {
        total:100,
        limit:10,
        page:1,
        list:[
          {id:1},
          {id:2},
          // {id:3},
          // {id:4},
          // {id:5},
        ],
        tableData:[],
        index:null,
        uuid:null,
        select_table:[
          {
            agentId: null,
            createTime: "2023-12-22 11:42:53",
            failNum: 0,
            id: 26,
            manifestNo: "B-2023122200015",
            notPrintedNum: 1,
            operator: null,
            orderNumbers: 1,
            printedNum: 0,
            successNum: 0,
            userId: null,
            userName:"随便公司",
          }
        ], //选中的批次
        printStatusList:[ //打印状态选项
          {label:'未打印' , value:0},
          {label:'已打印' , value:1}
        ],
        formInline:{
          printStatus:null,
          manifestNo:null,
          startTime:null,
          endTime:null,
          dataTimevalue:[]
        },
        socket:null,
        printers:null,
        defaultPrinter:null,
        waybillNO:'000000000000',
        printTaskId:0,
        waybillTemplateURL:process.env.VUE_APP_BASE_API + '/printer/middle'
      }
    },

    created() {
    },
    mounted() {
      this.getList()
      this.doConnect()
    },
    destroyed() {

    },
    methods: {
      doConnect() {
          this.socket = new WebSocket('ws://127.0.0.1:13528');
          var result = "打印成功";
          var tmptaskID = "0";
          var that = this

          // 打开Socket
          console.log(this.socket)
          that.socket.onopen = function (event) {
              // 监听消息
              that.socket.onmessage = function (event) {
                  var data = JSON.parse(event.data);
                  that.printers = data.printers;
                  that.defaultPrinter = data.defaultPrinter;
                  if (data.cmd == 'notifyPrintResult') {
                      var result = "打印成功";
                      if (data.taskID != tmptaskID) {
                          for (var i = 0; i < data.printStatus.length; i++) {
                              if (data.printStatus[i].status == 'failed') {
                                  result = "打印失败";
                                  break;
                              } else if (data.printStatus[i].status == 'canceled') {
                                  result = "取消打印任务";
                                  break;
                              }
                          }
                          tmptaskID = data.taskID;
                          console.log(result);
                      }
                  } else if (data.cmd == "print") {
                      if (data.previewURL)
                          window.open(data.previewURL);
                  }

              };
              // 监听Socket的关闭
              that.socket.onclose = function (event) {
                  console.log("打印机失去联系，请刷新网页重新连接");
              };
          };
          that.socket.onerror = function (event) {
              console.log("打印机出现问题,请联系客服");
          }
      },

       doPreview() {
          var printData = this.getPrintData();
          printData.task.preview = true;
          console.log('开始预览' , printData)
          this.socket.send(JSON.stringify(printData));

      },
      //打印电子面单
       doPrint() {
          var printData = this.getPrintData();
          this.socket.send(JSON.stringify(printData));
      },
      getPrintData() {
          this.waybillNO = "123456789123";
          this.printTaskId = parseInt(1000 * Math.random());
          var request = {
              cmd: "print",
              requestID: "12345678901234567890",
              version: "1.0",
              task: {
                   taskID: '' + this.printTaskId,
                   preview: false,
                   printer: this.defaultPrinter,
                   notifyMode: "allInOne",
                   previewType:'pdf',
                   documents: [
                    {
                        "documentID": this.waybillNO,
                        contents: [
                            //电子面单部分
                            {
                                templateURL: this.waybillTemplateURL,
                                signature: "MD:kw4V6Gtj/7ZasLyotby+HA==",
                                "data": {
                                    "recipient": {
                                        "address": {
                                            "city": "济南市",
                                            "detail": "解放东路100号",
                                            "district": "历下区",
                                            "province": "山东省"
                                        },
                                        "mobile": "13888888888",
                                        "name": "张三",
                                        "phone": "13888888888"
                                    },
                                    "routingInfo": {
                                        "consolidation": {
                                            "name": "济南",
                                            "code": "jinan"
                                        },
                                        "origin": {
                                            "code": "STO"
                                        },
                                        "sortation": {
                                            "name": "济南"
                                        },
                                        "routeCode": "380D-56-04"
                                    },
                                    "sender": {
                                        "address": {
                                            "city": "东营市",
                                            "detail": "广兴路300号",
                                            "district": "垦利县",
                                            "province": "山东省"
                                        },
                                        "mobile": "13412341234",
                                        "name": "仓库",
                                        "phone": "13412341234"
                                    },
                                    "waybillCode": "773224859224902"
                                }
                                //电子面单数据
                            }
                        ]
                    }
                  ]
              }
          };
          return request;
      },
        getUUID(len, radix) {
            var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
            var uuid = [], i;
            radix = radix || chars.length;
            if (len) {
                for (var i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
            } else {
                var r;
                uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
                uuid[14] = '4';
                for (var i = 0; i < 36; i++) {
                    if (!uuid[i]) {
                        r = 0 | Math.random() * 16;
                        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                    }
                }
            }
            return uuid.join('');
        },















      resetForm(formName) {
        this.formInline={
          printStatus:null,
          manifestNo:null,
          startTime:null,
          endTime:null,
          dataTimevalue:[]
        }
        this.getList()
      },
      dataTimeChange(e){
        this.formInline.startTime=e[0]
        this.formInline.endTime=e[1]
      },
     pullOrderNum(index=0 , uuid=''){
       var arr = []
       if(this.select_table.length<=0){
         this.$message({
           type:'error',
          message:this.$t('public.Please_select_batch_number')
         })
         return
       }
       this.select_table.forEach((item,index)=>{
         arr.push(item.manifestNo)
       })
       var data = {
         manifestNos:arr,
         index:index,
         uuid:uuid
       }
       var that = this
       var res_code = null
       var res_msg = null
       manifest_dataCheck(data).then(res=>{
          manifest_billing(res.datas).then(req=>{
            res_code = req.code
            res_msg = req.msg
            if(res.code==200){
              if(req.code == 0){
                this.$message({
                  type:'success',
                  message:res_msg
                })
                that.getList()
              }else{
                this.$message({
                  type:'error',
                  message:res_msg
                })
              }
            }
            if(res.code == 0){
              if(req.code == 0){
                 this.pullOrderNum(res.index , res.uuid)
              }else{
                this.$message({
                  type:'error',
                  message:res_msg
                })
              }
            }
          })
       })
     },
     manifest_billing(list){

     },
      getList(){
        var data = {
          page:this.page,
          limit:this.limit,
          printStatus:this.formInline.printStatus,
          manifestNo:this.formInline.manifestNo,
          startTime:this.formInline.startTime,
          endTime:this.formInline.endTime,
        }
        manifest_list(data).then(res=>{
          this.tableData = res.page.list
          this.total = res.page.totalCount
        })
      },
      handleSelectionChange(e){
        console.log(e)
        this.select_table = e
      },
      handleSizeChange(e){
        this.limit = e
        this.getList()
      },
      handleCurrentChange(e){
        this.page = e
        this.getList()
      }
    }
  }
</script>

<style scoped>
  @import url('Waybill_printing.css');
  .box{
    overflow: scroll;
    height: 100vh;
  }
  .item{
    width: 100mm;
    height: 113mm;
    background: pink;
  }
  .item_box{
    padding: 2mm;
    box-sizing: border-box;
    border:1px solid #333
  }
</style>
